#include <iostream>
#include <unistd.h>
#include <queue>
#include <pthread.h>
#include "LockGuard.hpp"
const int defaultCap = 5;
template<class T>
class Blockqueue
{
public:
    Blockqueue(int capacity = defaultCap)
    :_capacity(capacity)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_consumer_cond, nullptr);
        pthread_cond_init(&_product_cond, nullptr);
    }

    bool isFull()
    {
        return _block_queue.size() == _capacity;
    }

    bool isEmpty()
    {
        return _block_queue.size() == 0;
    }
    void push(T& task)
    {
        LockGuard lockguard(&_mutex);
        while(isFull())
        {
            pthread_cond_wait(&_product_cond, &_mutex);
        }
        _block_queue.push(task);
        pthread_cond_signal(&_consumer_cond);
        sleep(1);
    }

    void pop(T& out)
    {
        LockGuard lockguard(&_mutex);
        while(isEmpty())
        {
            pthread_cond_wait(&_consumer_cond, &_mutex);
        }
        out = _block_queue.front();
        _block_queue.pop();
        pthread_cond_signal(&_product_cond);
        sleep(1);
    }
    ~Blockqueue()
    {
        delete _product_cond;
        delete _consumer_cond;
        delete _mutex;
    }
private:
    std::queue<T> _block_queue;
    pthread_cond_t _product_cond;
    pthread_cond_t _consumer_cond;
    pthread_mutex_t _mutex;
    int _capacity;
};